package com.atguigu.security.config;

import com.sun.javafx.scene.traversal.Algorithm;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @author 0x_Jss
 * @date 2022年02月16日 10:16
 * @description
 */
@Component
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return privateEncode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String s) {
        //明文密码加密
        String formPassword = privateEncode(rawPassword);
        //声明数据库密码
        String databasePassword = s;
        //作比较
        return Objects.equals(formPassword,databasePassword);
    }

    //抽取通用方法
    private String privateEncode(CharSequence rawPassword){
        try {
            String algorithm = "MD5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

            byte[] input = ((String)rawPassword).getBytes();
            //加密
            byte[] output = messageDigest.digest(input);

            String encoded = new BigInteger(1,output).toString(16).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String privateEncode = new MyPasswordEncoder().privateEncode("123123");
        System.out.println(privateEncode);
    }
}